package cn.org.processor.guestbook.admin.service.impl;

import cn.org.processor.guestbook.admin.mapper.MessageMapper;
import cn.org.processor.guestbook.admin.model.response.PageResponse;
import cn.org.processor.guestbook.admin.service.MessageService;
import entity.Message;
import io.Page;
import io.Response;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import util.PageUtil;

import java.util.List;

@Service
@Slf4j
public class MessageServiceImpl implements MessageService {
    private final MessageMapper messageMapper;

    public MessageServiceImpl(MessageMapper messageMapper) {
        this.messageMapper = messageMapper;
    }

    @Override
    public Response list(Page page) {
        int total = messageMapper.getCount();

        int start = PageUtil.getStartRows(page);
        List<Message> list = messageMapper.list(start, page.getOffset());

        PageResponse response = new PageResponse();
        response.setTotal(total);
        response.setList(list);

        return Response.builder().ret(Response.Ret.SUCCESS).msg("获取成功").data(response).build();
    }

    @Override
    public Response lock(Integer id) {
        Message message = messageMapper.findById(id);
        if (message == null) {
            return Response.builder().ret(Response.Ret.FAILURE).msg("留言不存在").build();
        }

        Message update = new Message();
        update.setId(id);
        update.setStatus(Message.Status.INVISIBLE);
        if (messageMapper.update(update) > 0) {
            return Response.builder().ret(Response.Ret.SUCCESS).msg("操作成功").build();
        }

        log.error("Failed to lock message {}", message);
        return Response.builder().ret(Response.Ret.FAILURE).msg("操作失败").build();
    }

    @Override
    public Response unlock(Integer id) {
        Message message = messageMapper.findById(id);
        if (message == null) {
            return Response.builder().ret(Response.Ret.FAILURE).msg("留言不存在").build();
        }

        Message update = new Message();
        update.setId(id);
        update.setStatus(Message.Status.VISIBLE);
        if (messageMapper.update(update) > 0) {
            return Response.builder().ret(Response.Ret.SUCCESS).msg("操作成功").build();
        }

        log.error("Failed to lock message {}", message);
        return Response.builder().ret(Response.Ret.FAILURE).msg("操作失败").build();
    }

}
